#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <msg_queue.h>
#include <tools.h>
#include <string.h>
#include "bank.h"

// 子进程数量
#define CHILD_CNT 9

// 子进程可执行文件
static char* child_process[] = {
	"create",
	"destroy",
	"login",
	"transf",
	"modify",
	"save",
	"unlock",
	"take",
	"query",
};
	
// 存储子进程ID
static pid_t child_pid[CHILD_CNT];

// 消息队列描述符
int msgfd;

void sigfunc(int signum)
{
	printf("主进程收到异常信号!\n");
	for(int i=0; i<CHILD_CNT; i++)
	{
		printf("主进程向子进程%s发送SIGINT信号!\n",child_process[i]);
		kill(child_pid[i],SIGINT);
	}

	printf("主进程删除消息队列！\n");
	remove_msg(msgfd);

	printf("主进程退出！\n");
	exit(EXIT_SUCCESS);
}

int main(int argc,const char* argv[])
{


	int log_fd = open(LOG_PATH,O_WRONLY|O_CREAT,0644);
	if(0 > log_fd)
	{
		printf("打开日志文件失败，open:%m\n");
		return EXIT_FAILURE;
	}
	
	dup2(log_fd,STDIN_FILENO);


	printf("绑定SIGINT信号处理函数\n");
	for(int sig=SIGHUP; sig<=SIGRTMAX; sig++)
	{
		signal(sig,sigfunc);
	}

	msgfd = create_msg(MSG_KEY);
	printf("创建消息队列成功,msgfd=%d\n",msgfd);

	for(int i=0; i<CHILD_CNT; i++)
	{
		child_pid[i] = vfork();
		if(0 == child_pid[i])
			execl(child_process[i],child_process[i],NULL);
		printf("加载子进程：%s 进程号:%u\n",child_process[i],child_pid[i]);
	}

	int status;
	pid_t pid;
	while(EXIT_FAILURE != (pid = wait(&status)))
	{
		printf("子进程：%u，exit status is %d\n",pid,WEXITSTATUS(status));
	}
	return 0;
}
